﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using SD.IBUS;
using SD.BUS;
using SD.Entities;
using System.Data.SqlClient;

namespace SD.UI
{
    public partial class AddOrganization : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                TabContainer1.ActiveTabIndex = Convert.ToInt32(Session["indexTab"]);
            }
            else
            {
                ShowDetail2();
                ShowDetail3();
            }
        }

        protected void chkExpOfInterest_CheckedChanged(object sender, EventArgs e)
        {
            if (chkExpOfInterest.Checked)
            {
                tabsDetail3.Visible = true;
                TabContainer1.ActiveTabIndex = 2;
                
                // Bind data to textbox, when checkbox has autopostback envent, 
                // values in textbox are not miss or change. 
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
               
            }
            else
            {
                tabsDetail3.Visible = false;
            }
        }

        protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
        {
            Session["indexTab"] = TabContainer1.ActiveTabIndex;
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("ShowOrganizationList.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            // Create IOrganizationBIZ object
            IOrganizationBIZ iOrganizationBIZ = new OrganizationBIZ();
            // Create Organization object
            Organization organization = new Organization();

            // Detail 1
            organization.Name = tbxOrgName.Text;

            // Create the list of organization
            List<Organization> listOrganization = new List<Organization>();

            // Check the duplication of organization name
            try
            {
                listOrganization = iOrganizationBIZ.GetOrgByName(organization.Name.ToString().Trim());
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            // Check Organization name has existed in database
            if (listOrganization.Count > 0)
            {
                ShowMessage("Organization name has existed in system. Please input another name.");
                
                // Load values to enable textbox
                tbxAddressLine1.Text = hdfLine1.Value;
                tbxAddressLine2.Text = hdfLine2.Value;
                tbxAddressLine3.Text = hdfLine3.Value;
                tbxPostcode.Text = hdfPostCode.Value;
                tbxCityTown.Text = hdfTown.Value;
                tbxCounty.Text = hdfCountry.Value;
                tbxNationCountry.Text = hdfCountry.Value;
                tbxTypeOfBussiness.Text = hdfBussiness.Value;
                tbxSICCode.Text = hdfSicCode.Value;
                tbxLeadContact.Text = hdfContactName.Value;
            }
            else
            {
                organization.ShortDescription = tbxOrgShortDes.Text;
                organization.IsPreferred = chkPreOrganization.Checked;
                organization.IsExpressionOfInterest = chkExpOfInterest.Checked;
                organization.FullDescription = tbxOrgFullDescription.Text;
                organization.Phone = tbxPhoneNumber.Text;
                organization.Fax = tbxFax.Text;
                organization.Email = tbxEmail.Text;
                organization.Web = tbxWebAddress.Text;
                organization.Charity = tbxCharityNumber.Text;
                organization.Company = tbxCompanyNumber.Text;

                // Create Address object
                Address address = new Address();
                // Bind value to object
                address.AddressId = txtAddressID.Value;
                organization.Address = address;

                // Create ReferenceData object
                ReferenceData referenceData = new ReferenceData();
                // Bind value to object
                referenceData.RefId = txtBussinessID.Value;
                organization.BusinessType = referenceData;

                // Create Contact object
                Contact contact = new Contact();
                // Bind value to object
                contact.ContactId = txtContactID.Value;
                organization.Contact = contact;

                organization.IsActive = true;

                // Detail 2
                // Create Details 2 object
                try
                {
                    organization.Details2 = GetDetail2();
                }
                catch (SqlException)
                {
                    ShowMessage(ERROR_SQL_EXCEPTION);
                }
                catch (Exception)
                {
                    ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
                }

                // Detail 3
                // Create Detail 3 object
                organization.Programmes = new List<Programme>();
                organization.Services = new List<Service>();

                // Detail 4
                // Create Detail 4 object
                organization.SupportingMaterials = new List<SupportingMaterial>();

                // Detail 5
                // Create Direction object
                organization.Directorates = new List<Directorate>();

                // Insert new organization
                try
                {
                    iOrganizationBIZ.Insert(organization);
                }
                catch (SqlException)
                {
                    ShowMessage(ERROR_SQL_EXCEPTION);
                }
                catch (Exception)
                {
                    ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
                }

                // If insert successful
                ShowMessageAndRedirect("Insert Organization successful", "ShowOrganizationList.aspx");
            }
        }
        //---------------------------Show Detail2------------------------------
        private void ShowDetail2()
        {
            // Create IReferenceDataBIZ object
            IReferenceDataBIZ iRef = new ReferenceDataBIZ();
            // Create datatable OrgSpecialism
            DataTable dtOrgSpecialism;
            // Create datatable OrgSpecialism
            DataTable dtSerDisCapablities;
            // Create datatable OrgSpecialism
            DataTable dtSerBarrCapablities;
            // Create datatable OrgSpecialism
            DataTable dtSerBenCapablities;
            // Create datatable OrgSpecialism
            DataTable dtSerPerCirCapablities;
            // Create datatable OrgSpecialism
            DataTable dtSerEnthCapablities;
            // Create datatable OrgSpecialism
            DataTable dtAccredition;

            try
            {
                //Get all organization Specialism
                dtOrgSpecialism = iRef.ListReferenceDataByRefcode("Organisation Specicalism");

                // Bind data to checklist
                ckbOrgSpecicalism.DataSource = dtOrgSpecialism;
                ckbOrgSpecicalism.DataValueField = "RefID";
                ckbOrgSpecicalism.DataTextField = "RefValue";
                ckbOrgSpecicalism.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Services Disablities Capabilities
                dtSerDisCapablities = iRef.ListReferenceDataByRefcode("Service Disabilities Capabilities");

                // Bind data to checklist
                listSerDisCapabilities.DataSource = dtSerDisCapablities;
                listSerDisCapabilities.DataValueField = "RefID";
                listSerDisCapabilities.DataTextField = "RefValue";
                listSerDisCapabilities.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Services Barrires Capablities
                dtSerBarrCapablities = iRef.ListReferenceDataByRefcode("Service Barriers Capabilites");

                listSerBarCapablities.DataSource = dtSerBarrCapablities;
                listSerBarCapablities.DataValueField = "RefID";
                listSerBarCapablities.DataTextField = "RefValue";
                listSerBarCapablities.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Services Benefits Capablities
                dtSerBenCapablities = iRef.ListReferenceDataByRefcode("Service Benenfits Capabilites");

                listSerBeneCapablities.DataSource = dtSerBenCapablities;
                listSerBeneCapablities.DataValueField = "RefID";
                listSerBeneCapablities.DataTextField = "RefValue";
                listSerBeneCapablities.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Services Peronal Circumstances Capabilities
                dtSerPerCirCapablities = iRef.ListReferenceDataByRefcode("Service Personal Circumstances Capabilites");

                clistSerPerCirCapabilities.DataSource = dtSerPerCirCapablities;
                clistSerPerCirCapabilities.DataValueField = "RefID";
                clistSerPerCirCapabilities.DataTextField = "RefValue";
                clistSerPerCirCapabilities.DataBind();

            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Services Ethnicity Capablities
                dtSerEnthCapablities = iRef.ListReferenceDataByRefcode("Service Ethnicity Capabilites");

                listSerEthCapablities.DataSource = dtSerEnthCapablities;
                listSerEthCapablities.DataValueField = "RefID";
                listSerEthCapablities.DataTextField = "RefValue";
                listSerEthCapablities.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            try
            {
                //Get all Accreditation
                dtAccredition = iRef.ListReferenceDataByRefcode("Accreditation");

                listAccreditation.DataSource = dtAccredition;
                listAccreditation.DataValueField = "RefID";
                listAccreditation.DataTextField = "RefValue";
                listAccreditation.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }       
        }
        //---------------------------------------------------------------------
        //-----------------------------Show Detail3----------------------------
        private void ShowDetail3()
        {
            // Create ProgrammeBIZ object
            IProgrammeBIZ iproBIZ = new ProgrammeBIZ();
            // Create IServiceBIZ interface object
            IServiceBIZ iserBIZ = new ServiceBIZ();

            // Create datatable to store list Programme
            DataTable dtPro;
            // Create datatable to store list Service
            DataTable dtSer;

            // Catch exception of get programme
            try
            {
                // Get all Programme
                dtPro = iproBIZ.GetAll(false);

                // Bind data to listbox Programme
                clistEOIProgrammes.DataSource = dtPro;
                clistEOIProgrammes.DataTextField = "Name";
                clistEOIProgrammes.DataBind();
            }
            catch (SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch (Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }

            // Catch exception of get service
            try
            {
                // Get all Service
                dtSer = iserBIZ.GetAll(false);

                // Bind data to listbox Service
                clistEOIServices.DataSource = dtSer;
                clistEOIServices.DataTextField = "Name";
                clistEOIServices.DataBind();
            }
            catch(SqlException)
            {
                ShowMessage(ERROR_SQL_EXCEPTION);
            }
            catch(Exception)
            {
                ShowMessageAndRedirect(INFO_DATAHANDLE_SUCCESSFUL, "CommomError.aspx");
            }
        }
        //---------------------------------------------------------------------

        /// <summary>
        /// Set detail 2 for updated organization
        /// </summary>
        private List<ReferenceData> GetDetail2()
        {
            List<ReferenceData> lstDetail2 = new List<ReferenceData>();
            IReferenceDataBIZ refDate2BIZ = new ReferenceDataBIZ();

            try
            {

                // traverse over Org Specicalism
                foreach (ListItem item in ckbOrgSpecicalism.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // traverse over SerDisCapabilities
                foreach (ListItem item in listSerDisCapabilities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // Services Barrires Capablities
                foreach (ListItem item in listSerBarCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Benefits Capablities
                foreach (ListItem item in listSerBeneCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Peronal Circumstanc
                foreach (ListItem item in clistSerPerCirCapabilities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Services Ethnicity Capablities
                foreach (ListItem item in listSerEthCapablities.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }

                // bind Accreditation
                foreach (ListItem item in listAccreditation.Items)
                {
                    if (item.Selected)
                    {
                        lstDetail2.Add(refDate2BIZ.GetById(item.Value));
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lstDetail2;
        }
    }
}